package com.hopes.bizz.risk.aop;

import com.hopes.boss.admin.api.entity.SysTenant;
import com.hopes.boss.admin.api.feign.RemoteTenantService;
import com.hopes.boss.common.core.constant.SecurityConstants;
import com.hopes.boss.common.data.tenant.TenantBroker;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: ljh
 * @create: 2023/8/16
 */
@Aspect
@Component
@RequiredArgsConstructor
public class TenantJobAop {

    private final RemoteTenantService remoteTenantService;


    @Around(value = "@annotation(com.hopes.bizz.common.core.annotation.TenantJobRun)")
    public void aroundAdvice(ProceedingJoinPoint joinPoint)  {
        long start = System.currentTimeMillis();
        XxlJobHelper.log("----------------多租户任务----------------`");
        List<SysTenant> tenantList = remoteTenantService.list(SecurityConstants.FROM_IN).getData();
        for (SysTenant sysTenant : tenantList) {
            Long tenantId = sysTenant.getId();
            TenantBroker.runAs(tenantId, (id) -> {
                try {
                    XxlJobHelper.log("----------------运行租户id为:{}的任务----------------`", id);
                    long begin = System.currentTimeMillis();
                    joinPoint.proceed();
                    XxlJobHelper.log("----------------运行租户id为:{}的任务结束,结果为={},耗时(毫秒)={}----------------`",id, true, System.currentTimeMillis() - begin);
                } catch (Throwable e) {
                    XxlJobHelper.log("----------------运行租户id为:{}的任务执行错误----------------",id);
                }
            });
        }
        XxlJobHelper.log("----------------多租户任务结束,结果为={},耗时(毫秒)={}----------------`", true, System.currentTimeMillis() - start);
        // 设置任务结果
        XxlJobHelper.handleSuccess();
    }

}
